package edu.com.wjt219971332.controller;

import edu.com.wjt219971332.entity.Result;
import edu.com.wjt219971332.entity.Singer;
import edu.com.wjt219971332.entity.User;
import edu.com.wjt219971332.service.SingerService;
import edu.com.wjt219971332.service.UserService;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.UUID;
import java.util.stream.Collectors;

@Controller
@RequestMapping("singer")
public class singerController {
    @Autowired
    private SingerService singerService;
    @RequestMapping("show")
    public String show(){
        return "singer/querysinger";
    }

    @GetMapping
    @ResponseBody
    public Result queryByPage(Singer singer, @RequestParam("page") Integer page, @RequestParam("size")Integer size, @RequestParam(value = "sort", required = false)String sort) {
        PageRequest pageable = PageRequest.of(page-1, size);
        Page<Singer> result = this.singerService.queryByPage(singer, pageable);
        return Result.ok("获取成功！",  result.getTotalElements(), result.get().collect(Collectors.toList()));
    }
    @RequestMapping("/select")
    @ResponseBody
    public Result select(@RequestParam("name") String name){
        return  Result.ok("操作成功！", this.singerService.queryByusername(name));
    }

    @RequestMapping("/insertInit")
    public String registerInit(){
        return "singer/insert";
    }

    @RequestMapping("/insert")
    public String register(@ModelAttribute("singer") Singer singer, MultipartFile file){
        saveRegister(singer, file);
        singerService.insert(singer);
        return "redirect: ../login/loginInit";
    }

    @RequestMapping("/updateInit/{singerid}")
    public String updateInit(@PathVariable("singerid") Integer singerid
            , Model model){
        Singer singer = singerService.queryById(singerid);
        model.addAttribute("singer", singer);
        return  "singer/update";
    }
    @RequestMapping("/update")
    @ResponseBody
    public Result update(@ModelAttribute("singer") Singer singer, MultipartFile file){
        saveRegister(singer, file);
        return Result.ok("修改成功",this.singerService.update(singer));
    }

    @RequestMapping("/deleteInit/{singerid}")
    @ResponseBody
    public String deleteInit(@PathVariable("singerid") Integer singerid){
        singerService.deleteById(singerid);
        return "redirect:/login/loginshow";
    }

    @RequestMapping("/showPic/{fileName}.{suffix}")
    public void showPicture(@PathVariable("fileName") String fileName,
                            @PathVariable("suffix") String suffix,
                            HttpServletResponse response){
        File imgFile = new File("E:/test/fileupload" + fileName + "." + suffix);
        responseFile(response, imgFile);
    }
    public void saveRegister(Singer singer, MultipartFile file){
        if (file != null){
            // 生成图片存储的名称，UUID 避免相同图片名冲突
            String originalFileName = file.getOriginalFilename(); // 原始文件名
            String suffix = originalFileName.substring(originalFileName.lastIndexOf(".")); // 图片后缀
            String fileName = UUID.randomUUID().toString() + suffix;
            String filePath = "E:/test/fileupload" + fileName;
            File saveFile = new File(filePath);
            try {
                // 将上传的文件保存到服务器文件系统
                file.transferTo(saveFile);
                // 记录服务器文件系统图片名称
                singer.setPic(fileName);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    private void responseFile(HttpServletResponse response, File imgFile) {
        try(InputStream is = new FileInputStream(imgFile);
            OutputStream os = response.getOutputStream();){
            byte [] buffer = new byte[1024]; // 图片文件流缓存池
            while(is.read(buffer) != -1){
                os.write(buffer);
            }
            os.flush();
        } catch (IOException ioe){
            ioe.printStackTrace();
        }
    }
}
